<?php

//stop the direct browsing to this file - let index.php handle which files get displayed
checkLogin();

# Deal with op and add some basic sanity checking

#insert - process payment
#op=pay_selected_invoice means the user came from the print_view or manage_invoces
#op=pay_invoice means the user came from the process_paymen page

global $db_server;
global $auth_session;
if ( isset($_POST['process_payment']) ) {
	
        $invoice = new invoice();
        $invoice->sort="date";
        $invoice->customer = $_POST['customerId'];
        $invoice->query=$_REQUEST['query'];
        $invoice->qtype=$_REQUEST['qtype'];
        $invoice->having="money_owed";
	$sth = $invoice->select_all('', "ASC");

        $invoices = $sth->fetchAll(PDO::FETCH_ASSOC);
        
        $amount= floatval($_POST['amount']);
        $display_block="";
        $ok=true;
        foreach($invoices as $row){
            if($amount > 0 && $ok){
                $payment = new payment();
                $payment->ac_inv_id = $row['id'];
                $payment->ac_amount = $row['owing'] > $amount ? $amount :$row['owing'];
                $amount -= $row['owing'];
                $payment->ac_date=$_POST['ac_date'];
                $payment->ac_payment_type = $_POST['ac_payment_type'];
                $payment->ac_discount = $_POST['discount']/100;
                $payment->ac_paidWithDiscount = $_POST['paidWithDiscount'];
                $result = $payment->insert();
                $saved = !empty($result) ? "true" : "false";
                if($saved =='true'){
                        $display_block =  $LANG['save_payment_success'];
                } else {
                        $display_block =  "Se produjo un error al guardar el pago de la factura con id ".$row['id'].
                                ". Por favor intententelo nuevamente<br />";
                        $ok=false;
                }
            }
        }

	
}

$smarty->assign('display_block', $display_block);

$smarty -> assign('pageActive', 'payment');
$smarty -> assign('active_tab', '#money');
?>
